package org.broadway.integration.jmx.test;

import java.io.IOException;
import java.net.MalformedURLException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import javax.management.MBeanServer;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
import org.broadway.jmx.JmxException;

public class JmxTestUtil {
    public static void startJmxRmiServer(MBeanServer server, int port) {
        try {
            LocateRegistry.createRegistry(port);
            JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:"+ port + "/jmxrmi");
            JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server);
            cs.start();
        } catch (MalformedURLException ex) {
            throw new JmxException("Error while starting Agent: " + ex.getMessage());
        } catch (RemoteException ex) {
            throw new JmxException("Error while starting Agent: " + ex.getMessage());
        } catch (IOException ex) {
            throw new JmxException("Error while starting Agent: " + ex.getMessage());
        }
    }
}
